package com.baichang.taoshunda.service.impl;

import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.utils.MathUtils;
import com.baichang.taoshunda.dao.CompanyBalanceDao;
import com.baichang.taoshunda.entity.Bussiness;
import com.baichang.taoshunda.entity.CompanyBalance;
import com.baichang.taoshunda.entity.Order;
import com.baichang.taoshunda.service.*;
import com.baichang.taoshunda.utils.ConvertTypeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CompanyBalanceServiceImpl implements CompanyBalanceService {

    @Autowired
    private CompanyBalanceDao companyBalanceDao;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private CashService cashService;

    @Autowired
    private UserBankService userBankService;

    @Autowired
    private ParamsService paramsService;

    /**
     * 根据日期查看商家账单
     *
     * @param bussId    商家编号
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param nowPage
     * @param pageSize
     * @return 列表
     */
    @Override
    public Map<String, Object> findBussinessBills(Integer bussId, String startDate, String endDate, Integer nowPage, Integer pageSize) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> maps = companyBalanceDao.findBussinessBills(bussId, startDate, endDate, nowPage, pageSize);
        Bussiness bussiness = businessService.getBusinessById(bussId);
        //
        map.put("billList", maps);
        //计算总收入
        BigDecimal allMoney = new BigDecimal(0);
        if (maps != null && maps.size() > 0) {
            for (Map<String, Object> everyMap : maps) {
                String balanceState = everyMap.get("balanceState").toString();
                Double money = ConvertTypeUtils.obj2Double(everyMap.get("balance"));
                if (balanceState.equals("+")) {
                    allMoney = BigDecimal.valueOf(MathUtils.add(allMoney.doubleValue(), money));
                } else if (balanceState.equals("-")) {
                    allMoney = BigDecimal.valueOf(MathUtils.sub(allMoney.doubleValue(), money));
                }
            }
        }
        map.put("allMoney", allMoney);
        map.put("freezeMoney", bussiness.getFreezeMoney());
        map.put("allCount", maps.size());
        return map;
    }

    /**
     * 查看商家钱包信息
     *
     * @param bussinessId 商家编号
     * @return
     */
    @Override
    public Map<String, Object> findBussinessWallet(Integer bussinessId) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        Bussiness bussiness = businessService.getBusinessById(bussinessId);
        map.put("balance", bussiness.getBalance());
        map.put("cashTime", paramsService.getParamsValue(29, 27).get("value"));
        //放入银行卡信息
        //如果有提现记录，放入最后一次提现银行卡信息
        List<Map<String, Object>> cashList = cashService.findCashHistoryByBussinessId(bussinessId);
        if (cashList != null && cashList.size() > 0) {
            Map<String, Object> cashMap = cashList.get(0);
            Integer bankcardId = ConvertTypeUtils.obj2Integer(cashMap.get("bankcardId"));
            Map<String, Object> userBank = userBankService.getUserBankById(bankcardId);
            map.put("bankCard", userBank);
        } else {
            //没有，默认排序第一张
            List<Map<String, Object>> mapList = userBankService.findBusinessBankCard(bussinessId);
            if (mapList != null && mapList.size() > 0) {
                Map<String, Object> userBank = mapList.get(0);
                map.put("bankCard", userBank);
            } else {
                map.put("bankCard", new HashMap<String, Object>());
            }
        }
        map.put("freezeMoney", bussiness.getFreezeMoney());
        return map;
    }

    /**
     * 商家接单的时候添加余额
     *
     * @param order     订单信息
     * @param bussiness 商家信息
     * @return
     */
    @Override
    public boolean saveCompanyBalance(Order order, Bussiness bussiness) {
        int souceType = 1;
        String state = "+";
//        return saveCompanyBalance(order, bussiness, souceType, state, order.getAllMoney().subtract(order.getFee()).subtract(order.getDispatching()), bussiness.getBalance().add(order.getAllMoney()).subtract(order.getFee()).subtract(order.getDispatching()));
        Double addMoney = MathUtils.sub(order.getAllMoney().doubleValue(), order.getFee().doubleValue(), order.getDispatching().doubleValue());
        Double allMoney = MathUtils.add(bussiness.getBalance().doubleValue(), addMoney);
        return saveCompanyBalance(order, bussiness, souceType, state, order.getAllMoney().subtract(order.getFee()).subtract(order.getDispatching()), BigDecimal.valueOf(allMoney));
    }

    /**
     * 商家退款
     *
     * @param order
     * @param bussiness
     * @return
     */
    @Override
    public boolean saveReturnMoney(Order order, Bussiness bussiness) {
        int souceType = 2;
        String state = "-";
        return saveCompanyBalance(order, bussiness, souceType, state, order.getAllMoney(), bussiness.getBalance().subtract(order.getAllMoney()));
    }

    /**
     * 商家提现
     *
     * @param bussiness
     * @param money
     * @return
     */
    @Override
    public boolean saveCash(Bussiness bussiness, Double money) {
        CompanyBalance companyBalance = new CompanyBalance();
        companyBalance.setCurrentAmount(bussiness.getBalance().subtract(BigDecimal.valueOf(money)));
        companyBalance.setBussId(bussiness.getId());
        companyBalance.setBalance(BigDecimal.valueOf(money));
        companyBalance.setSourceType(3);
        companyBalance.setCreated(new Date());
        companyBalance.setBalanceState("-");
        return companyBalanceDao.save(companyBalance) > 0;
    }

    @Override
    public boolean saveReturnGoods(Order order, Bussiness bussiness) {
        return saveCompanyBalance(order, bussiness, 4, "-", order.getAllMoney().subtract(order.getFee()).subtract(order.getDispatching()), bussiness.getBalance().subtract(order.getAllMoney()).subtract(order.getFee()).subtract(order.getDispatching()));
    }

    /**
     * 修改余额
     *
     * @param order     订单信息
     * @param bussiness 商家信息
     * @param souceType 来源 1接单2退款3提现 4退货
     * @param state     状态
     * @param allMoney
     * @param balance
     * @return
     */
    private boolean saveCompanyBalance(Order order, Bussiness bussiness, int souceType, String state, BigDecimal balance, BigDecimal allMoney) {
        CompanyBalance companyBalance = new CompanyBalance();
        companyBalance.setCurrentAmount(allMoney);
        companyBalance.setOrderNumber(order.getOrderNumber());
        companyBalance.setBussId(bussiness.getId());
        companyBalance.setBalance(balance);
        companyBalance.setSourceType(souceType);
        companyBalance.setCreated(new Date());
        companyBalance.setBalanceState(state);
        return companyBalanceDao.save(companyBalance) > 0;
    }
}
